
//
//  CZdetailViewController.swift
//  GZWeibo666
//
//  Created by wu on 16/05/1.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

import SVProgressHUD

import SVPullToRefresh

class CZdetailViewController: UIViewController,CZStatusBottomViewDelegate, UITableViewDataSource, UITableViewDelegate
{
    //MARK:属性
    
    var status : CZStatus? {
        didSet{
            loadNewComments((status?.id)!,click: false)
        }
    }
    
    
    
    //MARK: 准备UI
    override func viewDidLoad()
    {
        super.viewDidLoad()
        
        prepareUI()
        
    }
    
    
    let CellReuseIdentifier = "CellReuseIdentifier"
    let CellBlankCell = "CellBlankCell"
    
    private func prepareUI()
    {
        /**
        注册cell
        */
        tableView.registerClass(CZBlankCell.self, forCellReuseIdentifier: CellBlankCell)
        tableView.registerClass(CZDetailCell.self, forCellReuseIdentifier: CellReuseIdentifier)
        tableView.registerClass(CZStatusNormalCell.self, forCellReuseIdentifier: CZStatusReuseIdentifier.NormalCell.rawValue)
        tableView.registerClass(CZStatusForwardCell.self, forCellReuseIdentifier: CZStatusReuseIdentifier.ForwardCell.rawValue)
        
        /**
        设置frame
        */
        UIScreen.width()
        tableView.frame = CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height - 30)
        

        //遵守代理
        tableView.delegate = self
        tableView.dataSource = self
        
        //取消分割线
        // tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        tableView.separatorStyle = UITableViewCellSeparatorStyle.SingleLine
            
        // 设置预估行高
        tableView.estimatedRowHeight = 330
        // 自动计算行高
        tableView.rowHeight = UITableViewAutomaticDimension
        
        
        //底部下拉加载评论
        tableView.addInfiniteScrollingWithActionHandler { () -> Void in
            print("加载更多评论")
            self.loadMoreComments((self.status?.id)!)
        }
        
        
        view.backgroundColor = UIColor.brownColor()
        
        
        //添加tableView
        view.addSubview(tableView)
        
        //底部view
        prepareBottomView()
    }
    
    //MARK: 数据源/代理
    func numberOfSectionsInTableView(tableView: UITableView) -> Int
    {
        return 2
    }
    
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        //当第0组
        if section == 0
        {
            return 1
        }
        else
        {
            if currentComments.count == 0
            {
                return 1
            }
            else
            {
                return currentComments.count
            }
        }
    }
    
    /**
    cell的内容
    */
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        //当第一组,显示一个cell,cell里面的内容是传进来的评论数据
        if indexPath.section == 0
        {
            let cell = tableView.dequeueReusableCellWithIdentifier(status!.cellId()) as! CZStatusCell
            
            //赋值模型
            cell.status = status
            
            //            print("status: \(status)")
            
            //设置回调
            cell.pushBlockCallback = {() -> Void in
                
                let detailVc = CZdetailViewController()
                //把模型赋值给详情控制器
                detailVc.status = self.status!.retweeted_status
                //隐藏底部tabbar
                detailVc.hidesBottomBarWhenPushed = true
                //push到详情控制器
                self.navigationController?.pushViewController(detailVc, animated: true)
            }
            
            return cell
        }
        
        
        //评论cell
        
        if self.currentComments.count == 0
        {
            let cell = tableView.dequeueReusableCellWithIdentifier(CellBlankCell) as! CZBlankCell
            cell.textLabel?.text = "还未加载到评论"
            return cell
        }
        
        let cell = tableView.dequeueReusableCellWithIdentifier(CellReuseIdentifier) as! CZDetailCell
        
        cell.commants = self.currentComments[indexPath.row]
        
        
        return cell
    }
    
    
    /**
    设置headerView
    */
    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        //当第一组的时候,设置一个headerView
        if section == 1
        {
            let headView = loadNewCommentsViews
            return headView
        }
        
        return nil
    }
    
    
    /**
    设置headerView高度
    */
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 1
        {
            return 44;
        }
        else
        {
            return 0
        }
    }
    
    
    /**
    设置评论行高
    */
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
    {
        if indexPath.section == 0
        {
            
            if status!.rowHeight != nil {
                
                return status!.rowHeight!
            }
            
            // 能到下面来,说明没有缓存的行高
            
            // 获取cell, 计算行高,并不会显示出来
            let cell = tableView.dequeueReusableCellWithIdentifier(status!.cellId()) as! CZStatusCell
            
            // cell计算行高
            let rowHeight = cell.rowHeight(status!)
            
            // 缓存行高
            status!.rowHeight = rowHeight
            
            // 返回行高
            
            return rowHeight
            
        }
        
        //评论行高
        if self.currentComments.count == 0
        {
            return 44
        }
        
        
        let comments = currentComments[indexPath.row]
        
        if comments.rowHeight != 0
        {
            return comments.rowHeight
        }
        
        // 能到下面来,说明没有缓存的行高
        
        // 获取cell, 计算行高,并不会显示出来
        let cell = tableView.dequeueReusableCellWithIdentifier(CellReuseIdentifier) as! CZDetailCell
        
        // cell计算行高
        let rowHeight = cell.rowHeight(comments)
        
        // 缓存行高
        comments.rowHeight = rowHeight
        
        // 返回行高
        
        return rowHeight
    }
    
    //MARK: 评论处理
    /// 要显示的评论数据
    var currentComments: [CZDetailCommant]  = [CZDetailCommant]()
        {
        didSet {
            // 刷新tableView的数据
            tableView.reloadData()
        }
    }
    
    
    ///评论按钮点击
    func commentButtonClick()
    {
        
        let count = self.currentComments.count ?? 0
        
        if count == 0
        {
            SVProgressHUD.showErrorWithStatus("当前微博没有评论")
            return
        }
        
        
        SVProgressHUD.showInfoWithStatus("正在加载最新评论,请稍候...")
        
        CZDetailCommant.loadCommants((status?.id)!, since_id: 0, max_id: 0) { (commants, error) -> () in
        }
        
        loadNewComments((status?.id)!,click: true)
        
    }
    
    // MARK: 加载评论数据
    func loadNewComments(id:Int,click:Bool) {
        
        
        let since_id = currentComments.first?.id ?? 0
        
        // 加载评论数据
        CZDetailCommant.loadCommants(id, since_id: since_id, max_id: 0, finished: { (commants, error) -> () in
            
            // 判断是否有错误
            if error != nil
            {
                SVProgressHUD.showErrorWithStatus("网络不给力")
                return
            }
            
            if since_id > 0
            {  // 加载新的评论数据
                // 最终的数据 = 新的数据 + 现有的数据
                self.currentComments = commants! + self.currentComments
                
                //没有最新评论
                if  commants!.count == 0
                {
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                        
                        SVProgressHUD.showSuccessWithStatus("已是最新评论")
                    })
                    
                }
                    
                else
                {
                    
                    /**
                    遍历子控件
                    */
                    for button in self.loadNewCommentsViews.subviews
                    {
                        //获得按钮
                        if button.self is UIButton
                        {
                            //设置标题
                            let button1 = button as! UIButton
//                            let counts = self.tableView.numberOfRowsInSection(1)
                            let counts = self.status!.comments_count + self.currentComments.count
                            button1.setTitle("评论 \(counts)", forState: UIControlState.Normal)
                            button1.sizeToFit()
                        }
                    }
                    
                    let height = ((self.status?.rowHeight)! - 65) as CGFloat
                    
                    if self.tableView.contentOffset.y < height
                    {
                        //刷新
                        self.tableView.reloadSections(NSIndexSet(index: 1), withRowAnimation: UITableViewRowAnimation.Fade)
                        return
                    }
                    //大于偏移值,跳到第一组
                    self.tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 1), atScrollPosition: UITableViewScrollPosition.Top, animated: true)
                }
            }
            else
            {    // 第一次加载20条数据
                // 赋值给属性
                self.currentComments = commants!
            }
        })
    }
//    func scrollViewDidScroll(scrollView: UIScrollView) {
//        print(self.tableView.contentOffset)
//        print("rowheight:\(self.status?.rowHeight)")
//    }
    
    // MARK: 加载更多评论数据
    func loadMoreComments(id:Int) {
        
        // 获取max_id
        let max_id = currentComments.last?.id ?? 0
        
        CZDetailCommant.loadCommants(id, since_id: 0, max_id: max_id, finished: { (commants, error) -> () in
            // 加载完数据,结束上拉加载更多数据,让菊花停止旋转
            self.tableView.infiniteScrollingView.stopAnimating()
            
            let count = self.currentComments.count ?? 0
            
            if count == 0
            {
                SVProgressHUD.showErrorWithStatus("没有加载到更多的数据")
                return
            }
            
            // 拼接数据
            // 总的数据 = 现有数据 + 获取到的更多数据
            self.currentComments = self.currentComments + commants!
            print("上拉加载数据完成,总共有: \(self.currentComments.count) 条数据")
        })
    }
    
    
    //MARK: 懒加载控件
    
    
    //懒加载评论view
    lazy var loadNewCommentsViews : UIView =
    {
        let loadNewCommentsView = UIView(frame: CGRect(x: 0, y: 0, width: 375, height: 44))
        
        loadNewCommentsView.backgroundColor = UIColor(white: 0.95, alpha: 1)
        
        //设置评论按钮
        let commentButton = UIButton()
        
        commentButton.setTitle("评论 \(self.status!.comments_count)", forState: UIControlState.Normal)
        
//        var count = UITableView.numberOfRowsInSection
        
        commentButton.setTitle("评论\(self.status!.comments_count)", forState: UIControlState.Normal)
        commentButton.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
        commentButton.addTarget(self, action: "commentButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        commentButton.frame = CGRect(x: 8, y: 4, width: 40, height: 44)
        commentButton.sizeToFit()
        
        loadNewCommentsView.addSubview(commentButton)
        
        return loadNewCommentsView
        }()
    
    
    //懒加载tableView
    lazy var tableView : UITableView =
    {
        let tableView = UITableView(frame: CGRectZero, style: UITableViewStyle.Plain)
        
        return tableView
        }()
    
    //准备bottomView
    func prepareBottomView()
    {
        //        tabBarController?.tabBar.bounds.size.height = 44
        view.addSubview(bottomView)
        view.bringSubviewToFront(bottomView)
        bottomView.frame = CGRectMake(0,UIScreen.mainScreen().bounds.height - 44 , UIScreen.mainScreen().bounds.width, 44)
    }
    
    
    //懒加载底部按钮
    private lazy var bottomView :CZStatusBottomView =
    {
        let view = CZStatusBottomView()
        view.delegate = self
        return view
        }()
    
    
    //实现底部按钮的代理
    func CZStatusBottomViewModal(bottomView: CZStatusBottomView, clickBtn: UIButton)
    {
        print("点击");

        let controller = CZModalViewController(titleLabel: nil, userLabel: nil)
        
        if clickBtn.tag == CZStatusButtonViewType.forwardBtnType.rawValue
        {
            controller.titleLabel.text = "转发微博"
            controller.isRepost = true
        }
        
        if clickBtn.tag == CZStatusButtonViewType.commentBtnType.rawValue
        {
            controller.titleLabel.text = "评论微博"
            controller.isRepost = false
        }
        
        var screen_name = CZUserAccount.loadUserAccount()?.screen_name ?? "..."
        
        if screen_name.isEmpty
        {
            screen_name = (status?.user?.screen_name)!
        }
        /*
        let screen_name = CZUserAccount.loadUserAccount()?.screen_name ?? "iOS06"
        
        let homeTitleButton = CZHomeTitleButton(title: screen_name)
        
        navigationItem.titleView = homeTitleButton
        */
        
        //显示当前用户的名称
        controller.userLabel.text = screen_name
        controller.repostStatusId = (status?.id)!
        
        presentViewController(UINavigationController(rootViewController: controller), animated: true) { () -> Void in
            print("modal")
        }
    }
}
